package com.online.music.handeler;

import cn.dev33.satoken.exception.NotLoginException;
import com.online.music.common.Result;
import com.online.music.exception.BaseException;
import jakarta.validation.ConstraintViolationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;


/**
 * 全局异常处理器，处理项目中抛出的业务异常
 *
 * @author Administrator
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 捕获业务异常
     *
     * @param ex Exception
     * @return Result
     */
    @ExceptionHandler(BaseException.class)
    public Result<String> exceptionHandler(BaseException ex) {
        log.error("异常信息", ex);
        return Result.error(ex.getMessage());
    }

    /**
     * sa-token未登录
     */
    @ExceptionHandler(NotLoginException.class)
    public Result<String> unauthorized(NotLoginException e) {
        log.error("未登录：{}", e.getMessage());
        return Result.error("未登录！请重新登录！");
    }

    @ExceptionHandler({SQLIntegrityConstraintViolationException.class})
    public Result<String> handleSQLIntegrityConstraintViolationException(SQLIntegrityConstraintViolationException ex) {
        String message = ex.getMessage();
        if (message.contains("Duplicate entry")) {
            String[] split = message.split(" ");
            String field = split[2];
            String msg = "呀呼，" + field + "已存在啦~";
            log.error("已存在:{}", msg);
            return Result.error(msg);
        } else {
            return Result.error("服务异常");
        }
    }

    /**
     * 数据校验失败异常处理
     *
     * @param ex MethodArgumentNotValidException
     * @return String
     */
    @ExceptionHandler({MethodArgumentNotValidException.class})
    public Result<String> handleMethodArgumentNotValidException(MethodArgumentNotValidException ex) {
//        BindingResult bindingResult = ex.getBindingResult();
//        StringBuilder sb = new StringBuilder("校验失败:");
//        for (FieldError fieldError : bindingResult.getFieldErrors()) {
//            sb.append(fieldError.getField())
//                    .append("-")
//                    .append(fieldError.getDefaultMessage())
//                    .append(", ");
//        }
//        String msg = sb.toString();
//        // 去掉最后一个逗号
//        msg = msg.substring(0, msg.length() - 2);
//        return Result.error(msg);
        return Result.error("参数校验失败");
    }

    /**
     * 数据校验失败异常处理
     *
     * @param ex ConstraintViolationException
     * @return String
     */
    @ExceptionHandler({ConstraintViolationException.class})
    public Result<String> handleConstraintViolationException(ConstraintViolationException ex) {
        return Result.error(ex.getMessage());
    }

}